package com.spark.tags;

import java.util.Map;

import com.spark.core.SparkBuilder;
import com.spark.core.SparkContext;
import com.spark.core.XMap;
@SuppressWarnings("unchecked")
public class MenuButton extends Button {
	
	public static final String TAG_NAME = "menuButton";
	
	public String PROPERTITY_MENU = "menu";
	public String PROPERTITY_ALIGN = "align";
	
	private static final String ASX_CLASS = "s-btn-asx";
	private static final String DEFAULT_TEMPLATES = "menuButton.ftl";
	
	public String getTemplate(){
		return DEFAULT_TEMPLATES;
	}
	
	public void init(XMap view, SparkContext context) throws Exception {
		super.init(view, context);
		String text = view.getString(PROPERTITY_TEXT, "");
		String iconClass = view.getString(PROPERTITY_ICON_CLASS, "");
		String asxCls = ASX_CLASS;
		if("".equals(text) && "".equals(iconClass)){
			asxCls = asxCls + "-e";
		}
		XMap menu = view.getChild(PROPERTITY_MENU);
		if(menu!=null){
			String id = (String)context.get(PROPERTITY_ID) + "_menu";
			menu.putString(PROPERTITY_ID, id);
			context.put(PROPERTITY_MENU, SparkBuilder.build(menu, context));
		}
		context.addJsonConfig(PROPERTITY_ALIGN,view.getString(PROPERTITY_ALIGN,"r"));
		context.put("asxCls", asxCls);
	}
	
	protected String build(SparkContext context){
		Map map = context.getMap();
		StringBuilder sb = new StringBuilder();
		sb.append("<div ").append(get(map,"tooltip")).append(" class=\"").append(get(map,"className")).append("\" style=\"width:").append(get(map,"width")).append("px;height:").append(get(map,"height")).append("px;line-height:").append(get(map,"height")).append("px;").append(get(map,"style")).append("\" id=\"").append(get(map,"id")).append("\">");
		sb.append("<span class=\"").append(get(map,"iconClass")).append("\">&nbsp;</span>");
		sb.append("<span class=\"").append(get(map,"textClass")).append("\">").append(get(map,"text")).append("</span>");
		sb.append("<span class=\"").append(get(map,"asxCls")).append("\">&nbsp;</span>");
		sb.append("</div>");
		sb.append(get(map,"menu"));
		sb.append("<script>new Spark.MenuButton(").append(get(map,"config")).append(");</script>");
		return sb.toString();
	}
}
